package movie.controller;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import movie.entity.Consumer;
import movie.entity.Member;
import movie.service.LoginService;
import movie.service.MemberService;

@Controller
public class MemberController {
	@Autowired
	private MemberService memberService;
	@RequestMapping(value = "/member", method = RequestMethod.GET)
	public String get(HttpServletRequest request, Model model) {
		HttpSession session = request.getSession();
		Consumer consumer = (Consumer)session.getAttribute("cur_user");
		int mid = consumer.getMemberId();
		String memberType = memberService.findMtype(mid);
		float discount = memberService.findDiscount(mid) * 10;
		model.addAttribute("memberType", memberType);
		model.addAttribute("discount", discount);
		return "/user/member";
	}
	
	
	@RequestMapping(value = "/recharge", method = RequestMethod.GET)
	public String get2(Model model) {
		List<Member> l = memberService.findAmember();
		model.addAttribute("mlist", l);
		return "/user/recharge";
	}
	
	@RequestMapping(value = "/recharged", method = RequestMethod.GET)
	public String get2(Model model, HttpServletRequest request) {
		String total_amount=request.getParameter("total_amount");
		float totalAmount=Float.parseFloat(total_amount);
		int recharge_type=getType(totalAmount) ;
		if(recharge_type != 0) {
			Calendar cal=Calendar.getInstance(); 
			HttpSession session = request.getSession();
			Consumer c = (Consumer)session.getAttribute("cur_user");
			if(c.getMemberId() != 1) {
				cal.setTime(c.getMemberDate());
			}
			cal.add(Calendar.DAY_OF_MONTH, 31);
			Date d = cal.getTime();
			
			c.setMemberId(recharge_type);
			c.setMemberDate(d);
			int rows = memberService.updateMember(c);
			model.addAttribute("memberType", memberService.findMtype(c.getMemberId()));
			float discount = memberService.findDiscount(c.getMemberId()) * 10;
			model.addAttribute("discount", discount);
		}
		return "/user/member";
	}
	public int getType(float totalAmount) {
		if(totalAmount>14.0f) {
			return 4;
		}
		else if(totalAmount>9.0f) {
			return 3;
		}
		else if(totalAmount>4.0f) {
			return 2;		
		}
		else {
			return 1;
		}
		
	}
}
